/**
 * 发送GET请求
 * @param {string} url     请求地址
 * @param {object} params  请求参数，格式：{参数名:值,...,参数名:值}
 * @param {object} headers  请求头自定义
 * @param {string} Type 返回的数据类型
 * @returns Promise
 */

function get(url, params = {}, headers = {}, Type = null)
{
    return new Promise((resolve, reject) => {

        const xhr = new XMLHttpRequest
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4){

                if (xhr.status === 200){

                    let res = xhr.responseText

                    if (Type === 'json')  res = JSON.parse(res)

                    resolve(res)
                } else  reject(xhr.status)
            }
        }
        let tempArr = []  
        for (let key in params) tempArr.push(`${key}=${params[key]}`) 

        xhr.open('get', `${url}?${tempArr.join('&')}`)

        for (let key in headers) xhr.setRequestHeader(key, headers[key])
        xhr.send(null)
    })
}

/**
 * 发送POST请求
 * @param {string} url     请求地址
 * @param {object} params  请求参数，格式：{参数名:值,...,参数名:值}
 * @param {object} headers  请求头自定义
 * @param {string} Type 返回的数据类型
 * @returns Promise
 */

function post(url, params = {}, headers = {}, Type = null)
{
    return new Promise((resolve, reject) => {

        const xhr = new XMLHttpRequest
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4){

                if (xhr.status === 200){

                    let res = xhr.responseText

                    if (Type === 'json')  res = JSON.parse(res)

                    resolve(res)
                } else  reject(xhr.status)
            }
        }
        let tempArr = []  
        for (let key in params) tempArr.push(`${key}=${params[key]}`) 

        xhr.open('post', url)
        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')

        for (let key in headers) xhr.setRequestHeader(key, headers[key])
        xhr.send(tempArr.join('&'))
    })
}